// pages/teacher-setup-information/index.js
const handler = require("../../utils/function.js");
const { $Message } = require('../../dist/base/index');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar: "../../images/index/teacher-avatar.png",
    nickname: "lucky",
    gender_list: [
      { name: '1', value: '男', checked: 'true' },
      { name: '0', value: '女' },
    ],
    gender: 0,
    sign: "",
    address: "",
    video:"",
    certificate:[],//上传资格证书
    delete_upload:true,
    image:"",
     
    oldfile:[],
    oldvideo:'',
    upImg:[],
    spinShow: true,
    visible1: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData();
  },
  initData: function () {
    // wx.showLoading({
    //   title: '加载中...',
    // })
    var that = this;
    var para = {
      "user_id": wx.getStorageSync('user_info').id,
      "user_type": wx.getStorageSync('user_info').user_type
    };
    handler.requestData("getUserInfo", para, function (res) {
      // wx.hideLoading();
      that.setData({ spinShow:false});
      if (res.success == true) {
        var temp = that.data.gender_list;
        for (var i = 0; i < temp.length; i++) {

          if (temp[i]['name'] == res.data.sex) {
            temp[i]['checked'] = true;
          } else {
            temp[i]['checked'] = false;
          }
        }
        var temp_certificate = res.data.user_certificate;
        var certificate = [];
        for(var i =0; i<temp_certificate.length; i++){certificate.push(temp_certificate[i]['file_path'])}
        // console.log(res,"11222222222222222222222");
        that.setData({
          // spinShow: false,
          gender_list: temp,
          avatar: res.data.avatar,
          nickname: res.data.nick_name,
          gender: res.data.sex,
          sign: res.data.signature,
          address: res.data.address,
          video:res.data.video_introduction_path,
          certificate: res.data.user_certificate,

          oldfile: certificate,
          oldvideo: res.data.video_introduction_path
        })
        wx.hideNavigationBarLoading(); //完成停止加载
        wx.stopPullDownRefresh(); //停止下拉刷新
      } else {
        wx.showToast({
          title: res.message,
          icon: 'loading'
        })
      }
    });
  },
  upload_avatar: function (res) {
    const that = this;
    wx.showLoading({
      title: '上传中...',
    })
    handler.uploadImageHandler((res) => {
      wx.uploadFile({
        url: 'http://xyds.4hl.cn/xyds/index.php/uploadImg',
        filePath: res[0],
        name: 'image',
        success: function (res) {
          wx.hideLoading();

           that.setData({ avatar: res.data });
        }
      })
      
    })
  },
  // 获取昵称
  get_nickname: function (e) {
    var test_nickname = handler.regTest(e.detail.value, "请输入姓名");
    test_nickname && this.setData({ nickname: e.detail.value });
  },
  //获取性别
  radioChange: function (e) {
    // console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({ gender: e.detail.value });
  },
  // 获取电话
  // get_phone: function (e) {
  //   var test_phone = handler.regTest(e.detail.value, "请输入正确的电话号码格式", /^1\d{10}$/);
  //   test_phone && this.setData({ phone: e.detail.value });
  // },
  // 获取地址
  get_address: function (e) {
    var test_address = handler.regTest(e.detail.value, "请输入地址");
    test_address && this.setData({ address: e.detail.value });
  },
  // 获取个性签名
  get_sign: function (e) {
    console.log(e.detail.value,'111111111111111');
    var test_sign = handler.regTest(e.detail.value, "请输入签名");
    test_sign && this.setData({ sign: e.detail.value });
  },
  // 上传图片
  uploadimg: function (data) {
    var imgLength = data.length;
    
    console.log(imgLength)
    if (imgLength >= 3) {
      $Message({
        content: '最多上传三张证书',
        type: 'error'
      })
      return;
    }
    wx.showLoading({
      title: '上传中...',
    })
    var that = this;
    var dataImg = "";

    for (var i = 0; i < data.length; i++) {
      wx.uploadFile({
        url: 'http://xyds.4hl.cn/xyds/index.php/uploadCertificate',
        filePath: data[i],
        name: 'file',
        success: function (res) {
          wx.hideLoading();
          var getArr = { "src": res.data, "status": true };
          that.data.certificate.push(getArr);
          that.setData({ certificate: that.data.certificate })
        },
        fail: function (res) {
          wx.hideLoading();
          $Message({
            content: '上传失败',
            type: 'error'
          })

        },
        complete: function (res) {

        }
      })
    }
  },
  // 上传证书
  image_upload:function(){

    const that = this;
    var tempImgArr = [];
    handler.uploadImageHandler((res) => {
      console.log(res)
      that.uploadimg(res);
    })
  },
  // choose_deleteImg 选择删除图片
  choose_deleteImg: function (e) {
    console.log(e.currentTarget.dataset.index);
    const index = e.currentTarget.dataset.index;
    const { certificate } = this.data;
    certificate[index].status = !certificate[index].status;
    this.setData({ certificate });
    console.log(this.data.certificate);
  },
  // delete_img 删除图片
  delete_img: function () {
    const { certificate } = this.data;
    var delete_index = [];
    var img_container = [];
    const that = this;
    for (var i = 0; i < certificate.length; i++) {
      certificate[i].status == false && (delete_index[delete_index.length] = certificate[i]);
      certificate[i].status == true && (img_container[img_container.length] = certificate[i]);
    }
    console.log(img_container);
    if (delete_index.length == 0) {
      $Message({
        content: '请选择要删除的图片',
        type: 'error'
      })
    } else {
      console.log(delete_index)
      wx.showModal({
        title: '',
        content: '确认是否删除？',
        success: function (e) {
          if (e.confirm) {
            that.setData({ certificate: img_container })
          }

        },
        fail: function () { }
      })

    }
  },
  // 上传视频
  video_upload:function(){
    const that=this;
    wx.showLoading({
      title: '上传中...',
    })
    handler.uploadVideoHandler((res)=>{
      wx.uploadFile({
        url: 'http://xyds.4hl.cn/xyds/index.php/uploadVedio',
        filePath: res,
        name: 'file',
        success: function (res) {
          wx.hideLoading();
          var result = JSON.parse(res.data);

          if (result.success==true){
            that.setData({ video: result.data });
          }else{
            $Message({
              content:result.message,
              type: 'error'
            })
          }
          
        }
      })
      
    })
  },
  //判断证书和视频是否有改动若有需要审核
  judceModify:function(){

    var file = this.data.oldfile;
    var video = this.data.oldvideo;
  
    var newvideo = this.data.video;
    var newfile = this.data.certificate;

    var flag = this.compareArray(file,newfile);
    var flag1 = video == newvideo?true:false;
    if (flag && flag1)
    {
      return true;
    } else{
      return false;
    }
  },
  compareArray:function (a, b) {
    if(a.length !== b.length) {
      return false;
    }
    const length = a.length;
    for (let i = 0; i < length; i++) {
      if (!this.compare(a[i], b[i])) {
        return false;
      }
    }
     return true;
    },
  compare:function (a, b) {
      if(a === b) {
        return true;
      }

      if (typeof a !== typeof b || a === null || b === null) {
        return false;
      }

      if (Array.isArray(a)) {
        if (!Array.isArray(b)) {
          return false;
        }
        return compareArray(a, b);
      }

      if (typeof a === "object") {
        return compareObject(a, b);
      }
      return false;
    },
  // 获取信息
  get_information: function () {
    var flag = this.judceModify();

    const { avatar, nickname, gender, sign, address, phone, video, certificate} = this.data;
    var nickname_test = handler.regTest(nickname, "请输入昵称")
    var address_test = handler.regTest(address, "请输入地址");
    var sign_test = handler.regTest(sign, "请输入签名");
    var test_certificate = handler.regTest(certificate, "请上传证书");
    var test_video = handler.regTest(certificate, "请上传视频");
    var test_all = nickname_test &&address_test && sign_test &&  test_certificate && test_video;
    var submitJson ={
      avatar:avatar,
      nick_name: nickname,
      sex:gender,
      signature:sign,
      address: address,
      id:wx.getStorageSync('user_info').id,

      vedio:video,
      is_modify: flag,
      certificate: JSON.stringify(certificate)
    };
    if (test_all) {
      handler.requestData("tearchModifyProfile", submitJson, function (res) {
        if (res.success == true) {
           $Message({
              content:res.message,
              type: 'success',
              duration: 5
           });
          setTimeout(function () { handler.intoPageHandler("../personal-information/index");},5000)
          
        } else {
          $Message({
            content: res.message,
            type: 'error',
            duration: 10
          });
        }
      });
     
    } else {
      $Message({
        content: '信息输入有误，请重新输入',
        type: 'error',
        duration: 10
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.initData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})